package com.xiaoming.mojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeRequest;
import com.xiaoming.mojcodesandbox.model.ExecuteCodeResponse;
import com.xiaoming.mojcodesandbox.model.ExecuteMessage;
import com.xiaoming.mojcodesandbox.model.JudgeInfo;
import com.xiaoming.mojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class JavaNativeCodeSandboxOld implements CodeSandBox{
    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaCodeSandbox = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        String code = ResourceUtil.readStr("testCode.simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        executeCodeRequest.setLanguage("java");
        executeCodeRequest.setCode(code);
        ExecuteCodeResponse executeCodeResponse = javaCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }


    private static final long TIME_OUT=5000L;
    private static final String GLOBAL_CODE_DIR_NAME="tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME="Main.java";
    private static final List<String> blackList=Arrays.asList("exec");

    //用更少的空间存储更多的词汇 实现更高效的敏感词查找
    private static final WordTree WORD_TREE;
    static {
        WORD_TREE=new WordTree();
        WORD_TREE.addWords(blackList);
    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        /*DefaultSecurityManger defaultSecurityManger=new DefaultSecurityManger();
        System.setSecurityManager(defaultSecurityManger);*/
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        //根目录
        String userDir=System.getProperty("user.dir");
        //代码包目录
        String globalCodePathName=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;

        if(!FileUtil.exist(globalCodePathName))
        {
            FileUtil.mkdir(globalCodePathName);
        }
        //检验危险代码 黑名单中代码不允许编译
        FoundWord foundWord=WORD_TREE.matchWord(code);
        if(foundWord!=null)
        {
            System.out.println(foundWord.getFoundWord());
            return null;
        }
        //1.把用户代码隔离存放
        String  userCodeParentPath=globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        File file = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2.编译代码 得到class文件
        String compileCmd=String.format("javac -encoding utf-8 %s",file.getAbsoluteFile());
        try {
            Process process=Runtime.getRuntime().exec(compileCmd);
            String operationName="编译";
            ExecuteMessage executeMessage= ProcessUtils.runProcessAndGetMessage(process,operationName);
            System.out.println(executeMessage);
        }
        catch (Exception e) {
            return getErrorResponse(e);
        }
        //3.执行代码 获取运行结果
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd=String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            try {
                Process runProcess=Runtime.getRuntime().exec(runCmd);
                //危险代码处理 限制运行时间不超过5s
                new Thread(()-> {
                    try {
                        Thread.sleep(TIME_OUT);
                        runProcess.destroy();
                        System.out.println("超时了，结束！");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start() ;

                String operationName="运行";
                ExecuteMessage executeMessage= ProcessUtils.runProcessAndGetMessage(runProcess,operationName);
                executeMessageList.add(executeMessage);
                System.out.println(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }
        }
        //4.整理输出
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        List<String> outputList =new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage=executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage))
            {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());

        }
        //TODO
        Optional<Long> first = executeMessageList.stream().map(ExecuteMessage::getTime).sorted((t1,t2)-> Math.toIntExact(t2 - t1)).findFirst();
        Long time = null;
        if(!first.isPresent())
        {
           time=first.get();
        }
        JudgeInfo judgeInfo=new JudgeInfo();
        //judgeInfo.setMemory();
        judgeInfo.setTime(time);

        if(outputList.size()==executeMessageList.size())
        {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setJudgeInfo(judgeInfo);
        executeCodeResponse.setOutPutList(outputList);
        //5文件清理
        if(file.getParent()!=null)
        {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del ? "成功" : "失败"));
        }

        return executeCodeResponse;
    }
    //6错误处理 提升健壮性

    public ExecuteCodeResponse getErrorResponse(Throwable e)
    {
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        executeCodeResponse.setOutPutList(new ArrayList<>());
        return executeCodeResponse;

    }
}
